//生产者
package mq

import (
	"gitee.com/Cookie_XiaoD/go-filestore-server/config"
	"github.com/streadway/amqp"
	"log"
	"sync"
)

var initChannelLocker sync.Mutex

//initChannel 初始化通道
func initChannel() bool {
	log.Println("初始化RabbitMQ通道")
	if innerChannel != nil {
		return true
	}
	initChannelLocker.Lock()
	defer initChannelLocker.Unlock()
	innerConn, err := amqp.Dial(config.RabbitMQCfg.RabbitmqURL)
	if err != nil {
		log.Printf("连接rabbitmq错误：%v", err.Error())
		return false
	}
	innerChannel, err = innerConn.Channel()
	if err != nil {
		log.Printf("获取channel错误：%v", err.Error())
		return false
	}
	log.Println("初始化RabbitMQ通道成功")
	return true
}

//PushMessage:推送消息
func PushMessage(exchangeName, routingKey string, msg []byte) bool {
	if !initChannel() {
		return false
	}
	err := innerChannel.Publish(exchangeName, routingKey, false, false, amqp.Publishing{
		ContentType:  "appliaction/json",
		Body:         msg,
		DeliveryMode: 2, //持久化数据
	})
	if err != nil {
		log.Printf("发送消息到交换机异常：%v", err.Error())
		return false
	}
	return true
}
